#!/usr/bin/python
# -*- coding: utf-8 -*-
# Create at 2008-9-1
# Author: MK2[fengmk2@gmail.com]

"""7z extrator

7-Zip returns the following exit codes: 
Code       Meaning 
0        No error 
1        Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed. 
2        Fatal error (there is no such archive)
7        Command line error 
8        Not enough memory for operation 
255      User stopped the process 
"""

import os
import shutil
from subprocess import Popen, PIPE
import net4.utilities as util

Supported_formats = (
    u'.7z', u'.zip', u'.gz', u'.gzip', u'.tgz', u'.bz', u'.bzip2', u'.tbz2', u'.tbz',
    u'.tar', u'.rar', u'.cab', u'.arj', u'.z', u'.taz', u'.cpio', u'.rpm', u'.deb',
    u'.lzh', u'.lha', u'.chm', u'.chw', u'.hxs', u'.iso', 
    u'.msi', u'.msp', 
#    u'.doc', u'.xls', u'.ppt',
    u'.wim', u'.swm', u'.dmg', u'.xar', u'.hfs', 
#    u'.exe',
)

def extract(archive, to):
    """extract a archive"""
    assert isinstance(archive, basestring)
    assert isinstance(to, basestring)
    assert archive
    assert to
    cmd = u'7z'
    if util.is_windows():
        cmd = os.path.join(os.path.dirname(__file__), u'bin/7z/7za.exe')
    cmd_args = u'%s e %s -o%s -y' % (cmd, archive, to)
    p = Popen(cmd_args, shell=True, stdout=PIPE)
    r = p.wait()
    print p.stdout.read()
    return r

def extract_circle(archive, to=None):
    """循环解压，只要解压出来的还是能被7z解压的文件，则会一直解压"""
    if to is None:
        to = archive + u'_dir'
    r = extract(archive, to)
    if r == 0:
        for filepath in util.walkfiles(to):
            filename = os.path.basename(filepath)
            ext = os.path.splitext(filename)[1].lower()
            if u'_CAB' in filename or ext in Supported_formats:
                extract_circle(filepath)
    return r

def test():
    sample = os.path.join(os.path.dirname(__file__), u'temp/outlfltr.msp')#u'7ztest.7z')
    tempdir = os.path.join(os.path.dirname(__file__), u'temp/temp')
    r = extract(sample, tempdir)
    assert r == 0
    for filename in util.walkfiles(tempdir):
        print filename
#    shutil.rmtree(tempdir)
    
    r = extract_circle(sample, tempdir)
    assert r == 0
    for filename in util.walkfiles(tempdir):
        print filename
#    shutil.rmtree(tempdir)
    print 'test success.'
    
if __name__ == '__main__':
    test()